# -*- coding=utf-8 -*-

"""
fuwa model
"""
from framework.redi import RedisModel
from models.index import IndexModel
import tornado.httpclient
import json
import time

class FuwaListModel(RedisModel):
    """dddd"""

    def __init__(self):
        """super init"""
        super(FuwaListModel, self).__init__()

    def get_redis_db(self):
        """
        specified collection name
        :return: string
        """
        return 0

    def get_fuwa_list(self, page, size=50):
        """
         get all fuwa list from redis 
         and use fuwa id for page
         :param page: current page number
         :param size: size for page per
         :return list: records 
        """
        start = 100
        count = int(self.get("globalid")) - start
        pos = (page - 1) * size + start
        i = 1
        fuwa_list = list()
        while i <= size and pos <= count:
            # find key for fuwa
            # key is fuwa_i_ or fuwa_c_
            nature = 'i'
            key = 'fuwa_%s_%s' % (nature, pos)
            if not self.hexists(key, 'name'):
                nature = 'c'
                key = 'fuwa_%s_%s' % (nature, pos)
            fuwa = self.hgetall(key)
            fuwa["key"] = key
            fuwa['nature'] = nature
            fuwa['key_id'] = pos
            fuwa_list.append(fuwa)
            i += 1
            pos += 1
        # return dict for bootstarp datatable
        return {
            'data': fuwa_list,
            'recordsTotal': count,
            'recordsFiltered': count
        }

    def get_fuwa_info(self, fuwa_id):
        """get fuwa info from redis"""
        key = 'fuwa_i_%s' % fuwa_id
        if not self.hexists(key, "name"):
            key = 'fuwa_c_%s' % fuwa_id
        fuwa = self.hgetall(key)
        return fuwa

    def get_fuwa_kind_list(self, fuwa_kind, start, size=50):
        """get fuwa list for c and i"""
        # fuwa_kind fuwa_c_ fuwa_i_
        m = IndexModel()
        syncs = m.get_fuwa(0, 1)
        if not syncs:
            return
        sync = syncs[0]
        count = sync.get('fu_%s_count' % fuwa_kind)
        kind = 'fuwa_%s_' % fuwa_kind
        l = list()
        i = 0
        j = 0
        for key in self.keys():
            if key.find(kind) == 0:
                if i < start:
                    i += 1
                elif j < size:
                    fuwa = self.hgetall(key)
                    fuwa['key'] = key
                    fuwa['nature'] = fuwa_kind
                    fuwa['key_id'] = key.split('_')[2]
                    l.append(fuwa)
                    j += 1
                elif j >= size:
                    break
        return {
            'data': l,
            'recordsTotal': count,
            'recordsFiltered': count
        }

    def get_hide_list(self, kind, start, size):
        """get fuwa hide list"""
        key = 'fuwa_%s' % kind
        count = self.zcard(key)
        stop = start + size - 1
        datas = dict(recordsTotal=count, recordsFiltered=count)
        if start >= count:
            datas['data'] = list()
            return datas
        fuwas = self.zrange(key, start, stop)
        l = list()
        for fuwa_key in fuwas:
            fuwa = self.hgetall(fuwa_key)
            fuwa['key'] = fuwa_key
            fuwa['key_id'] = fuwa_key.split('_')[2]
            loc = self.geopos(key, fuwa_key)
            fuwa['lng'], fuwa['lat'] = loc[0][0], loc[0][1]
            l.append(fuwa)
        datas['data'] = l
        return datas

    def get_cau_list(self, kind, start, size):
        """get fuwa cauth list"""
        key = 'fuwa_cau_%s' % kind
        count = self.zcard(key)
        stop = start + size - 1
        datas = dict(recordsTotal=count, recordsFiltered=count)
        if start >= count:
            datas['data'] = list()
            return datas
        fuwas = self.zrange(key, start, stop)
        l = list()
        for fuwa_key in fuwas:
            fuwa = self.hgetall(fuwa_key)
            fuwa['key'] = fuwa_key
            fuwa['key_id'] = fuwa_key.split('_')[2]
            l.append(fuwa)
        datas['data'] = l
        return datas

    def get_awarded_list(self, start, size):
        """award list"""
        key = 'fuwa_awarded'
        count = self.zcard(key)
        stop = start + size - 1
        datas = dict(recordsTotal=count, recordsFiltered=count)
        if start >= count:
            datas['data'] = list()
            return datas
        fuwas = self.zrange(key, start, stop)
        l = list()
        for fuwa_key in fuwas:
            fuwa = self.hgetall(fuwa_key)
            fuwa['key'] = fuwa_key
            fuwa['key_id'] = fuwa_key.split('_')[2]
            l.append(fuwa)
        datas['data'] = l
        return datas


    def get_hide_loca(self):
        """get hide loca"""
        # ak = 'sjiqZ9MndXqeqI4a39TO5IQUf2i2GC7F'
        key = '3fe9a1dcb5edc154f4897e44677182c8'
        start_time = time.time()
        # locations = [u'广州']
        locations = [u'广州', u'佛山', u'东莞', u'深圳', u'江门', u'中山', u'珠海']
        data = list()
        for location in locations:
            # url = 'http://api.map.baidu.com/geocoder/v2/?address=%s&output=json&ak=%s' % (location, ak)
            url = r'http://restapi.amap.com/v3/geocode/geo?key=%s&address=%s' % (key, location)
            c = tornado.httpclient.HTTPClient()
            try:
                res = c.fetch(url)
            except tornado.httpclient.HTTPError as e:
                print 'err: %s' % str(e)
                continue
            c.close()
            loc = json.loads(res.body)
            lng, lat = 0, 0
            if loc['geocodes'][0]:
                lnglat = loc['geocodes'][0]['location'].split(',')
                lng, lat = lnglat[0], lnglat[1]
            # query lng lat
            fuwa_i_list = self.georadius('fuwa_i', lng, lat, 25, unit='km', withdist=True)
            print "fuwa_i use %s " % (time.time() - start_time)
            fuwa_c_list = self.georadius('fuwa_c', lng, lat, 25, unit='km', withdist=True)
            print "fuwa_c use %s " % (time.time() - start_time)
            data.append(dict(loc=location, count=len(fuwa_c_list) + len(fuwa_i_list)))
        return data

    def get_hide(self):
        """get hide"""
        ak = 'sjiqZ9MndXqeqI4a39TO5IQUf2i2GC7F'
        location = '广州'
        url = 'http://api.map.baidu.com/geocoder/v2/?address=%s&output=json&ak=%s' % (location, ak)
        return url
        # c = tornado.httpclient.AsyncHTTPClient()
        # c.fetch(url, self.get_location)
        # i_count = self.zcard('fuwa_i')
        # c_count = self.zcard('fuwa_c')
        # fuwa_i = self.zrange('fuwa_i', 0, i_count)
        # fuwa_c = self.zrange('fuwa_c', 0, c_count)
        # for fuwa in fuwa_i:
        #    print self.zscore('fuwa_i', fuwa)


    def get_hide_count(self):
        """get hide fuwa count"""
        return self.zcard('fuwa_i'), self.zcard('fuwa_c')

    def get_cau_count(self):
        """get cauth fuwa count"""
        return self.zcard('fuwa_cau_i'), self.zcard('fuwa_cau_c')
